<template>
  <div class="container">
    <h1 class="mb-4">区块链事件监听</h1>
    
    <div class="alert alert-info mb-4">
      <i class="bi bi-info-circle-fill me-2"></i>
      此页面显示系统中发生的所有链上交易事件，包括投资记录的创建、更新和删除。
    </div>
    
    <div class="card mb-4">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h3 class="mb-0">事件列表</h3>
        <button class="custom-btn custom-btn-secondary" @click="clearEvents">
          <i class="bi bi-x-circle"></i> 清空列表
        </button>
      </div>
      <div class="card-body p-0">
        <div v-if="events.length === 0" class="p-5 text-center">
          <i class="bi bi-activity" style="font-size: 3rem;"></i>
          <p class="mt-3">暂无事件记录</p>
          <p class="text-muted">
            当您创建、更新或删除投资记录时，相关事件将显示在此处
          </p>
        </div>
        
        <div v-else class="list-group list-group-flush">
          <div 
            v-for="(event, index) in events" 
            :key="index" 
            class="list-group-item list-group-item-action"
            :class="{
              'list-group-item-success': event.type === 'create',
              'list-group-item-warning': event.type === 'update',
              'list-group-item-danger': event.type === 'delete'
            }"
          >
            <div class="d-flex w-100 justify-content-between align-items-center">
              <h5 class="mb-1">
                <i :class="getEventIcon(event.type)" class="me-2"></i>
                {{ getEventTypeName(event.type) }}
              </h5>
              <small>{{ formatTime(event.timestamp) }}</small>
            </div>
            <p class="mb-1">{{ event.details }}</p>
            <div class="d-flex justify-content-between align-items-center">
              <small>
                <strong>ID:</strong> {{ event.id }} | 
                <strong>区块号:</strong> {{ event.blockNumber }}
              </small>
              <div>
                <router-link 
                  v-if="event.id" 
                  :to="`/detail/${event.id}`" 
                  class="custom-btn custom-btn-info me-2"
                >
                  <i class="bi bi-info-circle"></i> 详情
                </router-link>
                <button 
                  class="custom-btn custom-btn-secondary" 
                  @click="copyTxHash(event.txHash)"
                  title="复制交易哈希"
                >
                  <i class="bi bi-clipboard"></i> {{ formatTxHash(event.txHash) }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="card">
      <div class="card-header">
        <h3>实时监听</h3>
      </div>
      <div class="card-body">
        <p>
          <i class="bi bi-broadcast me-2"></i>
          正在监听区块链上的新事件...
        </p>
        <div class="form-check form-switch">
          <input class="form-check-input" type="checkbox" id="autoRefresh" v-model="autoRefresh">
          <label class="form-check-label" for="autoRefresh">自动刷新事件列表</label>
        </div>
      </div>
    </div>
    
    <!-- 复制成功提示 -->
    <div 
      v-if="showCopyAlert" 
      class="position-fixed bottom-0 end-0 p-3" 
      style="z-index: 5"
    >
      <div class="toast show bg-success text-white" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="toast-header bg-success text-white">
          <i class="bi bi-clipboard-check me-2"></i>
          <strong class="me-auto">复制成功</strong>
          <button 
            type="button" 
            class="btn-close" 
            @click="showCopyAlert = false" 
            aria-label="Close"
          ></button>
        </div>
        <div class="toast-body">
          交易哈希已复制到剪贴板
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useStore } from 'vuex';

export default {
  name: 'EventsView',
  setup() {
    const store = useStore();
    const autoRefresh = ref(true);
    const showCopyAlert = ref(false);
    const refreshIntervalId = ref(null);
    
    // 从Vuex获取事件列表
    const events = computed(() => store.getters.allEvents);
    
    // 事件图标
    const getEventIcon = (type) => {
      switch(type) {
        case 'create': return 'bi bi-plus-circle-fill text-success';
        case 'update': return 'bi bi-pencil-fill text-warning';
        case 'delete': return 'bi bi-trash-fill text-danger';
        default: return 'bi bi-question-circle-fill';
      }
    };
    
    // 事件类型名称
    const getEventTypeName = (type) => {
      switch(type) {
        case 'create': return '创建投资';
        case 'update': return '更新投资';
        case 'delete': return '删除投资';
        default: return '未知事件';
      }
    };
    
    // 格式化时间
    const formatTime = (timestamp) => {
      if (!timestamp) return '';
      
      const date = new Date(timestamp);
      return date.toLocaleString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    };
    
    // 格式化交易哈希（只显示前后几位）
    const formatTxHash = (hash) => {
      if (!hash) return '';
      
      if (typeof hash === 'string') {
        const prefix = hash.startsWith('0x') ? '' : '0x';
        const fullHash = prefix + hash;
        return `${fullHash.substring(0, 6)}...${fullHash.substring(fullHash.length - 4)}`;
      }
      return '未知哈希';
    };
    
    // 复制交易哈希到剪贴板
    const copyTxHash = (hash) => {
      if (!hash) return;
      
      // 如果是字符串，直接复制
      const textToCopy = typeof hash === 'string' 
        ? (hash.startsWith('0x') ? hash : `0x${hash}`)
        : '';
      
      navigator.clipboard.writeText(textToCopy)
        .then(() => {
          showCopyAlert.value = true;
          setTimeout(() => {
            showCopyAlert.value = false;
          }, 2000);
        })
        .catch(err => {
          console.error('复制失败:', err);
        });
    };
    
    // 清空事件列表
    const clearEvents = () => {
      // 这里不会清除Vuex中的事件，只是为了演示
      // 在实际应用中，可能需要添加一个mutation来清空事件列表
      if (confirm('确定要清空所有事件记录吗？')) {
        // store.commit('CLEAR_EVENTS');
        alert('此功能在实际应用中可用');
      }
    };
    
    // 组件挂载时设置自动刷新
    onMounted(() => {
      if (autoRefresh.value) {
        refreshIntervalId.value = setInterval(() => {
          // 这里可以添加自动刷新的逻辑
          console.log('自动刷新事件列表');
        }, 10000); // 每10秒刷新一次
      }
    });
    
    // 组件卸载时清除定时器
    onUnmounted(() => {
      if (refreshIntervalId.value) {
        clearInterval(refreshIntervalId.value);
      }
    });
    
    return {
      events,
      autoRefresh,
      showCopyAlert,
      getEventIcon,
      getEventTypeName,
      formatTime,
      formatTxHash,
      copyTxHash,
      clearEvents
    };
  }
}
</script>

<style scoped>
.list-group-item {
  transition: all 0.2s ease;
  border-left: 5px solid transparent;
}

.list-group-item:hover {
  transform: translateX(5px);
}

.list-group-item-success {
  border-left-color: #198754;
}

.list-group-item-warning {
  border-left-color: #ffc107;
}

.list-group-item-danger {
  border-left-color: #dc3545;
}

.toast {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style> 